/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-08-18 11:59:56
 * @LastEditors: 商晓彬
 * @LastEditTime: 2022-01-06 11:13:16
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { MessageService } from '@abp/message/message.service';
import { BomContentServiceProxy, BomEditList, BomEditParentData, BomDesignDetailDto } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { BomApprovalComponent } from '../../bom-approval/bom-approval.component';
import { MaterialSonComponent } from '../material-son/material-son.component';
import { LazyLoadEvent, TreeNode } from 'primeng/api';

@Component({
    selector: 'bomMaintain',
    templateUrl: './bom-maintain.component.html',
    styleUrls: ['./bom-maintain.component.less']
})
export class BomMaintainComponent extends AppComponentBase {
    @ViewChild('materialSon') materialSon: MaterialSonComponent;
    @ViewChild('bomApproval') bomApproval: BomApprovalComponent;
    //引入子组件
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() editData: any;  //行数据
    @Input() title: string;  //标题
    saving = false;
    active = false;
    codeFlag = false;
    treeData: any;
    selectedNode: any;
    parentTitle = '';
    sonTitle = '';
    rowdata = [];
    selectRow: any;
    addFlag: boolean = false;
    display = false;
    uploadedFiles = [];
    bomUsing = false;
    sonData: any;
    secondSon: any;
    sonType = undefined;
    propy = 0;
    form = { materialCode: '', materialname: '', model: '' };
    saveFlag = true;
    oldTree = undefined;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _bomContentServiceProxy: BomContentServiceProxy,
        private _fileDownloadService: FileDownloadService,
    ) {
        super(injector);
    }
    backToAdd(event) {
        if (event != undefined) {
            let result = this.getAddTreeChildren(this.oldTree, this.selectRow.id)
            for (const item of event) {
                let data = new BomEditList();
                data.children = [];
                data.data = item.data;
                result.children.push(data);
            };
        }
        this.treeData = this.oldTree;
    }
    getAddTreeChildren(data ,current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.data.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getAddTreeChildren(item.children, current);
            }
        }
        return result;
    }
    submitDetail(row) {
        let input = new BomDesignDetailDto();
        input.unit1BomDosage = row.unit1BomDosage;
        input.id = row.id;
        input.remark = row.remark;
        input.materialId = row.materialId;
        input.bomDesignId = row.bomDesignId;
        input.parentId = row.parentId;
        input.btid = row.btid;
        input.yearsNo = row.yearsNo;
        this._bomContentServiceProxy.updateChildrenNode(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
            });
    }
    repair(row) {
        this.getSonTreedata(row);
        this.bomUsing = true;
    }
    getSonTreedata(row) {
        this._bomContentServiceProxy.getBomChildTreeGrid(
            row.id,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.sonData = [];
                this.sonData.push(result);
                this.expandSonAll();
            });
    }
    backToApproval() {

    }
    saveEdit() {

    }
    saveToApproval() {

    }
    ngOnInit() {
    }
    selectStatus(value) {
        switch (value) {
            case 0:
                return '编制中';
            case 1:
                return '审核中';
            case 2:
                return '被驳回';
            case 3:
                return '已发布';
            case 4:
                return '已维护';
            case 5:
                return '待维护';
            default:
                return null;
        }
    }
    //保存任务
    save(): void {
        //获取实体
        this.close();
    }
    //打开弹窗
    onShown(): void {
        this.getTreedata();
    }
    //查看新增任务
    show(): void {
        if (this.title == 'BOM维护') {
            this.initEditInfo();
        } else {
            this.form.model = undefined;
            this.form.materialCode = undefined;
            this.form.materialname = undefined;
            this.addFlag = true;
        }
        this.active = true;
        this.modal.show();
    }
    //初始化修改数据
    initEditInfo() {
        this.addFlag = false;
    }
    getTreedata() {
        this.rowdata = [];
        this._bomContentServiceProxy.getBomChildTreeGrid(
            this.editData.btId,
            3
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.treeData = [];
                this.treeData.push(result);
                this.treeData[0].data.levelNum = 3;
                this.form.model = result.data.model;
                this.form.materialCode = result.data.materialNo;
                this.form.materialname = result.data.materialName;
                this.expandAll();
            });
    }
    expandAll() {
        for (const node of this.treeData) {
            this.TreeExpandRecursive(node, true);
        }
    }
    expandSonAll() {
        for (const node of this.sonData) {
            this.TreeExpandRecursive(node, true);
        }
    }
    private TreeExpandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.TreeExpandRecursive(childNode, isExpand);
            });
        }
    }
    //关闭事件
    close(): void {
        //清空form表单
        this.sonType = undefined;
        this.modalSave.emit(this.treeData);
        this.form.model = undefined;
        this.form.materialCode = undefined;
        this.form.materialname = undefined;
        this.active = false;
        this.treeData = [];
        this.rowdata = [];
        this.parentTitle = undefined;
        this.sonTitle = undefined;
        this.modal.hide();
    }
    addSon() {
        this.sonType = 1;
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(this.treeData[0].data);
        if (this.treeData[0].children.length != 0) {
            let i = { index: this.treeData[0].children.length };
            this.rowdata.push(i);
        }
        this.secondSon = this.editData;
        this.rowdata[0].sonLevel = 1;
        this.sonTitle = "物料选择";
        this.materialSon.show();
    }
    addSonData(row, node) {
        this.sonType = 2;
        this.secondSon = undefined;
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(row);
        if (node.node.children.length != 0) {
            let i = { index: node.node.children.length };
            this.rowdata.push(i);
        }
        if (row.materialPropertyName == '部件') {
            this.propy = 0;
        } else {
            this.propy = 1;
        }
        this.selectRow = row;
        this.oldTree = this.treeData;
        this.treeData = [];
        this.sonTitle = "物料选择";
        this.materialSon.show();
    }
    import(row) {
        this.rowdata = [];
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(row);
        this.display = true;
    }
    /**
    * 下载模板
    */
    down() {
        let url = "http://localhost:4200/assets/common/excel/DesignBom.xls";
        window.open(url);
        URL.revokeObjectURL(url);
    }
    myUploader(event) {
        let files = { data: undefined, fileName: event.files[0].name };
        files.data = event.files[0];
        if (this.saveFlag) {
            this.saveFlag = false;
            this._bomContentServiceProxy.getExcelToBomDesignContent(
                files,
                this.rowdata[1].id,
            ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.saveFlag = true;
                if (result.code == 1) {
                    this._messageService.success("导入成功！");
                    this.uploadedFiles = [];
                    this.display = false;
                    this.getTreedata();
                } else {
                    this._messageService.error(result.message);
                    this.uploadedFiles = [];
                    this.display = false;
                }
            });
        }
    }
    delete(row) {
        this.message.confirm(
            '确认删除这条数据吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._bomContentServiceProxy
                            .deleBomNode(row.id)
                            .subscribe((result) => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.getTreedata();
                                    this._messageService.success('删除成功');
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            }
        );

    }
    onHide(event) {
        this.bomUsing = false;
        this.sonData = [];
        this.getTreedata();
    }
}
